﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace ForecastManager.Controls
{
	/// <summary>
	/// Interaction logic for SnapshotList.xaml
	/// </summary>
	public partial class SnapshotWall
	{
		public SnapshotBrick SelectedSnapshotBrick;
		public string SnapshotDir;

		public event EventHandler SelectionChanged;

		public SnapshotWall()
		{
			InitializeComponent();
		}

		public void OnSelectionChanged(EventArgs e)
		{
			EventHandler handler = SelectionChanged;
			if (handler != null) handler(this, e);
		}

		public void PutBricks(List<Snapshot> snapshots)
		{
			if (Dispatcher.CheckAccess())
			{
				snapshots = snapshots
					.OrderByDescending(item => item.SnapshotDate)
					.ToList();

				ClearWall();

				foreach (var snapshot in snapshots)
				{
					SnapshotBrick brick = new SnapshotBrick(snapshot, SnapshotDir + snapshot.SnapshotName + ".bfs");
					brick.Select += brickSelect;
					ControlVisualRoot.Children.Add(brick);
				}
			}
			else
			{
				Dispatcher.BeginInvoke(new Action(() => PutBricks(snapshots)), new object[] {});
			}
		}

		/// <summary>
		/// События выбора кирпича.
		/// </summary>
		private void brickSelect(object sender, EventArgs e)
		{
			SnapshotBrick selectedBrick = (SnapshotBrick) sender;
			if (SelectedSnapshotBrick != null)
				SelectedSnapshotBrick.ClearSelection();
			SelectedSnapshotBrick = selectedBrick;
			OnSelectionChanged(new EventArgs());
		}

		/// <summary>
		/// Очистка стены.
		/// </summary>
		private void ClearWall()
		{
			ControlVisualRoot.Children.Clear();
		}
	}
}
